use std::collections::{BinaryHeap, HashMap};
use std::cmp::Reverse;
struct Solution {}

impl Solution {
  pub fn eaten_apples(apples: Vec<i32>, days: Vec<i32>) -> i32 {
    let mut heap = BinaryHeap::new();
    let mut counter: HashMap<i32, i32> = HashMap::new();
    let mut ret = 0;
    apples.iter().zip(days).enumerate().for_each(|(i,(c, d))| {
      if *c != 0 {
        if let Some(n) = counter.get_mut(&(d + i as i32)) {
            if *n == 0 {
                heap.push(Reverse(d + i as i32));
            }
            *n += *c;
        } else {
            counter.insert(d + i as i32, *c);
            heap.push(Reverse(d + i as i32));
        }
      }
      loop {
        if let Some(Reverse(t)) = heap.peek() {
          if *t > i as i32 {
            if let Some(n) = counter.get_mut(t) {
              if *n == 1 {
                heap.pop();
              } 
              *n -= 1; 
            }
            ret += 1;
            break;
          } else {
            heap.pop();
          }
        } else {
          break;
        }
      }
    });
    let mut now = apples.len() as i32;
    loop {
      if let Some(Reverse(t)) = heap.peek() {
        if *t > now {
          if let Some(n) = counter.get_mut(t) {
            if *n == 1 {
              heap.pop();
            }
            *n -= 1;
          }
          ret += 1;
          now += 1;
        } else {
          heap.pop();
        }
      } else {
        break;
      }
    }
    ret
  }
}